class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int n = prices.size();
            vector<vector<int>> f(n,vector<int>(3));
            vector<vector<int>> g(n,vector<int>(3));
            //初始化
            f[0][0] = -prices[0];
            g[0][0] = 0;
            for(int j = 1 ; j < 3 ;j++){
                f[0][j] = g[0][j] = -0X3f3f3f3f;
            }
            for(int i = 1 ; i < n ; i++){
                for(int j = 0 ; j < 3;j++){
                    f[i][j] = max(f[i-1][j],g[i-1][j]-prices[i]);
                    if( j==0 ){
                        g[i][j] = 0;
                    }else{
                        g[i][j] = max(g[i-1][j],f[i-1][j-1]+prices[i]);
                    }
                }
            }
            int ret = -0x3f3f3f3f;
            for(int i = 0 ; i < 3 ;i++){
                ret = max(ret,g[n-1][i]);
            }
            return ret;
        }
    };